<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" 
    :title="getTitle" 
    width="650px" 
    @ok="handleSubmit" 
    showFooter
    destroyOnClose
    @cancel="handleCancel"
    :defaultFullscreen="false"
  >
    <BasicForm @register="registerForm"/>
    <div style="height: 50px;"></div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { approvalInputFormSchemas } from './data';
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { savePermissionApproval , getPermissionApply } from '/@/api/sys/ram';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColEx } from '/@/components/Form/src/types';
  import { useUserStore } from "/@/store/modules/user"
  import * as TenantApi from '/@/api/sys/tenant'

  const userStore = useUserStore()
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register', 'close']);
  const attrs = useAttrs()
  const record = ref<any>({});

  const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 90,
    schemas: approvalInputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });
  
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    await resetFields();
    record.value = data.record
    setModalProps({ 
      confirmLoading: false, loading: true, 
      canFullscreen: false, maskClosable: false,
      zIndex: 200
    })
    try {
      record.value = await getPermissionApply({id: data.record.id}) || {} 
      updateSchema([
        {
          field: "resourceIds",
          componentProps: {
            api: TenantApi.listCurrentPackageMenuTree,
            immediate: true
          },
        }
      ])

      setFieldsValue({ ...record.value, resourceIds: record.value.resourceIds.split(',') })

    } finally {
      setModalProps({ loading: false})
    }
  });

  const getTitle = computed(() => '权限审批');
  const handleCancel = () => emit('close')
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({confirmLoading: true});
      console.log('form-values', values)
      await savePermissionApproval({ 
        id: values.id,
        status: values.status,
        refuseReason: values.refuseReason
      });
      closeModal();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      setModalProps({confirmLoading: false});
    }
  }
</script>
